<!-- 关于COS -->
<template>
  <view class="jumpPage" :style="{ height: windowHeight + 'px' }">
    <view class="jump" :style="{ height: windowHeight - 70 + 'px' }"><text class="skip">跳转中...</text></view>
  </view>
</template>

<script>
  import programSetting from '@/utils/programSetting'
  import api from "@/api/api";
  import tip from '@/utils/tip';
  import {
    MERCHANT_INFO,
    CUSTOMER_INFO,
    SYSTEM_INFO
  } from '@/utils/constant'
  export default {
    config: {
      navigationBarTitleText: '跳转中...',
    },
    data() {
      return {
        gooodsInfo: [],
        itemCode: '',
        merchantId: '',
        itemId: '',
        valueName: '',
        windowHeight: 0,
        valueId: '',
        scanUrl: '',
        userName: ''
      }
    },
    onLoad(option) {
      let that = this

      // 通过后台应用中心/二维码管理 生成的 二维码 用(option.q判断)
      if (option.q) {
        let scan_url = decodeURIComponent(option.q);

        this.scanUrl = scan_url;
        let splitURL = scan_url.split('?')[1]
        let geteveryParameter = splitURL.split('&')
        let item_code = geteveryParameter[0].split('=')[1];
        let value_name = geteveryParameter[1].split('=')[1];
        let user_name = geteveryParameter[2].split('=')[1];
        this.itemCode = item_code;
        this.valueName = value_name;
        this.userName = user_name;
        if (this.userName != '' && this.userName != undefined && this.userName != null) {
          uni.setStorageSync('userName', this.userName);
        }

        this.getItemDetail();
        this.getScanLog();
        let systemInfo = uni.getStorageSync(SYSTEM_INFO);
        this.windowHeight = systemInfo.windowHeight;

      } else if (option.scene) {
        let scene = decodeURIComponent(option.scene);

        let page = "/pages/home/home?preview=true";
        // cms配置页面生成的太阳码 逻辑判断Start  scene 对应的参数是页面设置的 链接标识 字段
        if(scene == 'home'){
          // 链接到首页
          page = "/pages/"+ scene + '/' + scene + "?preview=true";
          let jumpHomePage =  "/pages/"+ scene + '/' + scene
          getApp().globalData.cmsPreview = true;
          // uni.switchTab({
          if(!programSetting.customTabbar) {
            uni.switchTab({
              url: jumpHomePage
            })
          } else {
            uni.redirectTo({
              url: page
            })
          }
          // uni.relaunch({
          //   url: page
          // })

        } else if(scene.split("/").indexOf("cms") !== -1) {
          // 链接到cms/page页面
          page = "/pages/cms/page?identifier=" + scene + "&preview=true"
          uni.redirectTo({
            url: page
          });

        } else if(scene.split("-").length > 4) {
          //链接到具体商品详情页 scene=new-items-id-35852-273584
          page = "/pages/item/item?preview=true&id=" + scene.split("-")[3] + "&valueId=" + scene.split("-")[4];
          uni.redirectTo({
            url: page
          });

        } else if(scene.split("-").length > 3) {
          //链接到具体分类列表页面 new-items-lp-636 （兼容COS之前配置的页面）
          page = "/pages/item/categoryNew?preview=true&cateCode=" + scene.split("-")[3];

          uni.redirectTo({
            url: page
          });
        } else if(scene.split("-").indexOf('footer') != -1) {
          // 链接到分类lp查看底部lp scene=new-items-footer-lp-331 （兼容COS之前配置的页面）
          page = "/pages/item/categoryNew?preview=true&cateCode=" + scene.split("-")[4];

          uni.redirectTo({
            url: page
          });

          // END cms配置页面生成的太阳码 逻辑判断结束

        } else {
          // cloud 后台 应用中心/二维码管理 生成的太阳码 逻辑判断 Start (二维码通过 option.q判断)
          // 通过分销系统下载的 商品分销码 && 小程序 逻辑判断
          that.getParamsByScene(option.scene)
        }

      } else {
        // 默认链接到首页
        let page = "/pages/home/home?preview=true";
        let jumpHomePage = "/pages/home/home"
        getApp().globalData.cmsPreview = true;
        if(!programSetting.customTabbar) {
          uni.switchTab({
            url: jumpHomePage
          })
        } else {
          uni.redirectTo({
            url: page
          })
        }
        // uni.switchTab({
        // uni.relaunch({
        //   url: page
        // })

        // uni.redirectTo({
        //   url: page
        // });

        return false;
      }
    },
    methods: {
      getParamsByScene: async function(scene) {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        const json = await api.getParamsByScene({
          method: 'GET',
        }, scene);
        if (json.code === 1000) {
          const sceneInfo = JSON.parse(json.data.value)

          if (!!sceneInfo.utmSource) {
            // 记录分销商
            let sourceInfo = {
              'utmMedium': sceneInfo.utmMedium,
              'utmSource': sceneInfo.utmSource,
              'utmTerm': sceneInfo.utmTerm,
              'expirationTime': new Date().getTime() + 604800000
            }
            uni.setStorageSync('sourceInfo', sourceInfo);
            let logObj = {
              "merchantId": merchantInfo.cloudMerchantId,
              "utmCampaign": "",
              "utmContent": "",
              "utmMedium": sceneInfo.utmMedium,
              "utmSource": sceneInfo.utmSource,
              "utmTerm": sceneInfo.utmTerm
            }
            if (!customerInfo) {
              // 用户未绑定手机号 需要配置域名
              wx.request({
                url: 'https://pv.sohu.com/cityjson?ie=utf-8',
                success: function(e) {
                  var aaa = e.data.split(' ');
                  var bbb = aaa[4]
                  var ccc = bbb.replace('"', '')
                  var ddd = ccc.replace('"', '')
                  var eee = ddd.replace(',', '')
                  logObj.uid = eee

                  that.sourceLog(logObj)
                  if (sceneInfo.utmTerm == 'pdp') {
                    uni.redirectTo({
                      url: "/pages/item/item?id=" +
                        sceneInfo.item.itemId +
                        "&valueId=" +
                        sceneInfo.item.valueId +
                        '&valueName=' +
                        sceneInfo.item.valueName
                    });
                  } else {
                    uni.redirectTo({
                      url: '/' + sceneInfo.page
                    });
                  }
                },
                fail: function(e) {
                  if (sceneInfo.utmTerm == 'pdp') {
                    uni.redirectTo({
                      url: "/pages/item/item?id=" +
                        sceneInfo.item.itemId +
                        "&valueId=" +
                        sceneInfo.item.valueId +
                        '&valueName=' +
                        sceneInfo.item.valueName
                    });
                  } else {
                    uni.redirectTo({
                      url: '/' + sceneInfo.page
                    });
                  }
                }
              })
            } else {
              // 用户已绑定手机号
              logObj.uid = customerInfo.openId
              that.sourceLog(logObj)
              if (sceneInfo.utmTerm == 'pdp') {
                uni.redirectTo({
                  url: "/pages/item/item?id=" +
                    sceneInfo.item.itemId +
                    "&valueId=" +
                    sceneInfo.item.valueId +
                    '&valueName=' +
                    sceneInfo.item.valueName
                });
              } else {
                uni.redirectTo({
                  url: '/' + sceneInfo.page
                });
              }
            }
          } else {
            // 在cloud 后台 应用中心/二维码管理 生成的太阳码 跳转到PDP
            uni.redirectTo({
              url: "/pages/item/item?id=" +
                sceneInfo.itemId +
                "&valueId=" +
                sceneInfo.valueId +
                '&valueName=' +
                sceneInfo.valueName
            });
          }

        }
      },


      // 商户扫码记录
      sourceLog: async function(params) {
        let that = this;
        const sourceLogData = await api.sourceLog({
          method: 'POST',
          query: params
        });
        if (sourceLogData.code == 1000) {
          
        }
      },


      // 商户扫码记录
      getScanLog: async function() {
        let that = this;
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        const scanLogData = await api.scanLog({
          method: 'POST',
          query: {
            "itemCode": this.itemCode,
            "merchantId":merchantInfo.cloudMerchantId,
            "qrUrl": this.scanUrl,
            "userAgent": "mp",
            "userName": this.userName,
            "valueName": this.valueName
          }
        });
        if (scanLogData.code == 1000) {
          
        }
      },

      getItemDetail: async function() {
        let that = this;
        this.itemId = '';
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
        this.merchantId = merchantInfo.cloudMerchantId;
        const goodsInfo = await api.getGoodsInfo({}, this.itemCode, this.merchantId);
        if (goodsInfo.code === 1000) {
          let itemProperties = [];
          let gooodsJson = goodsInfo.data;
          this.itemId = gooodsJson.itemId;
          itemProperties = JSON.parse(gooodsJson.itemProperties)
          if (this.itemId) {
            that.getGoodsDetail(merchantInfo, this.itemId)
          }
        } else {
          uni.redirectTo({
            url: "/pages/util/pageNotFound"
          })
        }
      },

      // 商品详情信息
      getGoodsDetail: async function(merchantInfo, itemId) {
        let that = this;
		if (!itemId) {
		  uni.redirectTo({
		    url: '/pages/util/pageNotFound'
		  });
		  return false
		}
        const json = await api.goodsDetail({
          query: {
            merchant_id: merchantInfo.cloudMerchantId,
            store_id: merchantInfo.cloudMerchantStoreId
          }
        }, itemId);
        if (json.code === 1000) {
          let data = json.data;
          const skus = data.skus;
          //  isFront 1-- 颜色 0-- 尺码
          for (var i = 0; i < skus.length; i++) {
            if (skus[i].skuProperties[0].valueName == this.valueName) {
              this.valueId = skus[i].skuProperties[0].valueId
            }
          }
          if (this.valueId) {
            uni.redirectTo({
              url: "/pages/item/item?id=" + itemId + '&valueId=' + this.valueId + '&valueName=' +
                this.valueName
            })
          } else {
            uni.redirectTo({
              url: "/pages/util/pageNotFound"
            })
          }
        }
      },

    }

  }
</script>


<style lang="less" scoped>
.jumpPage {
  width: 100%;
}

.jump {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30rpx;
}
</style>
